import { useState, useEffect, useRef } from 'react'
import { useHistory } from 'react-router-dom'

import { useDispatch, useSelector } from 'react-redux'
import {
  getUserProfile,
  getUpdataProfile,
  onUpdataPhoto,
  Logout,
} from '@/store/actions'
import { RootState } from '@/types/store'

import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import styles from './index.module.scss'
import dayjs from 'dayjs'

const Item = List.Item

const ProfileEdit = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const inpRef = useRef<HTMLInputElement>(null)

  // 控制生日弹出层
  const [visibleBirthday, setVisibleBirthday] = useState(false)

  // 昵称、简介弹出层类型
  type InputPopup = {
    type: '' | 'name' | 'intro'
    value: string
    visible: boolean
  }

  // 性别、图片弹出层类型
  type ListsPopup = {
    type: '' | 'photo' | 'gender'
    visible: boolean
  }

  // 控制性别、图片弹出层
  const [ListPopup, setListPopup] = useState<ListsPopup>({
    type: '',
    visible: false,
  })

  // 控制昵称、简介弹出层
  const [inputPoup, setInputPoup] = useState<InputPopup>({
    type: '',
    value: '',
    visible: false,
  })

  // 关闭修改昵称简介弹出层
  const inputHidden = () =>
    setInputPoup({
      type: '',
      value: '',
      visible: false,
    })

  // 开启修改昵称或简介弹出层
  const inputShow = (type: InputPopup['type'], value: InputPopup['value']) => {
    setInputPoup({
      type,
      value,
      visible: true,
    })
  }

  // 关闭修改性别、图片弹出层
  const ListHidden = () =>
    setListPopup({
      type: '',
      visible: false,
    })

  // 开启修改性别、图片弹出层
  const ListShow = (type: ListsPopup['type']) => {
    setListPopup({ type, visible: true })
  }

  // 更新昵称/简介/性别/生日等
  const onUpdateProfile = async (
    type: 'name' | 'intro' | 'gender' | 'photo' | 'birthday',
    value: string
  ) => {
    if (type === 'photo') {
      // 单独修改头像的逻辑
      inpRef.current?.click()
    } else {
      // 昵称、简介、性别
      await dispatch(getUpdataProfile({ [type]: value }))
      inputHidden()
      ListHidden()
      Toast.show({
        content: '更新成功',
        duration: 600,
        afterClose: () => {
          history.push('/profile/edit')
        },
      })
    }
  }

  // 单独处理图片文件
  const onChangeFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e)
    if (!e.target.files) return
    const formData = new FormData()

    formData.append('photo', e.target.files[0])

    await dispatch(onUpdataPhoto(formData))

    Toast.show({
      content: '图片更新成功',
      duration: 600,
      afterClose: () => {
        ListHidden()
      },
    })
  }

  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])

  // 时间过滤
  const ontime = (value: string) => {
    return dayjs(value).format('YYYY-MM-DD')
  }

  // 更新时间
  const onUpdataBirthday = (value: Date) => {
    const time = dayjs(value).format('YYYY-MM-DD')
    onUpdateProfile('birthday', time)
  }

  // 退出登录
  const onLogout = () => {
    Dialog.show({
      title: '温馨提示',
      content: '亲,一定要退出吗！',
      // closeOnAction是点击操作后关闭弹窗
      closeOnAction: true,
      // closeOnMaskClick  点击遮蔽罩关闭弹窗
      closeOnMaskClick: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            style: {
              color: '#999',
            },
          },
          {
            key: 'confirm',
            text: '确认',
            style: {
              color: 'red',
            },
            onClick: () => {
              dispatch(Logout())
              Toast.show({
                content: '退出成功',
                duration: 600,
                afterClose: () => {
                  history.push('/login')
                }
              })
            },
          },
        ],
      ],
    })
  }

  // 获取个人信息
  const { photo, name, gender, birthday, intro } = useSelector(
    (state: RootState) => state.profile.userProfile
  )
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          className="nav-bar"
          onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              // extra 表示右侧的额外信息
              onClick={() => {
                ListShow('photo')
              }}
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      photo || 'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              arrow
            >
              <input type="file" hidden ref={inpRef} onChange={onChangeFile} />
              头像
            </Item>
            {/* 函数传参拿到要求数据 */}
            <Item arrow onClick={() => inputShow('name', name)} extra={name}>
              昵称
            </Item>
            <Item
              arrow
              onClick={() => inputShow('intro', intro ?? '')}
              extra={
                <p className={classNames('intro', 'normal')}>
                  {intro || '未填写'}
                </p>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={gender + '' === '0' ? '男' : '女'}
              onClick={() => ListShow('gender')}
            >
              性别
            </Item>
            <Item
              arrow
              extra={ontime(birthday)}
              onClick={() => setVisibleBirthday(true)}
            >
              生日
            </Item>
          </List>

          <DatePicker
            visible={visibleBirthday}
            onClose={() => setVisibleBirthday(false)}
            onConfirm={onUpdataBirthday}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={onLogout}>
            退出登录
          </Button>
        </div>
      </div>

      {/* 修改昵称/简介的弹窗层 */}
      <Popup visible={inputPoup.visible} position="right">
        <EditInput
          key={inputPoup.type}
          type={inputPoup.type}
          onClose={inputHidden}
          value={inputPoup.value}
          onUpdateName={onUpdateProfile}
        />
      </Popup>

      {/* 修改性别/头像弹出层 */}
      <Popup visible={ListPopup.visible} onMaskClick={ListHidden}>
        <EditList
          onClose={ListHidden}
          type={ListPopup.type}
          onUpdateProfile={onUpdateProfile}
        />
      </Popup>

      {/* 生日弹出层 */}
    </div>
  )
}

export default ProfileEdit
